import Request from '../../common/request'

function wxPromisify(fn) {
  return function(obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }
      obj.fail = function (res) {
        reject(res)
      }
      fn(obj)
    })
  }()
}
/* 登录请求 */
function Login(code, userRes) {
  return Request('Xcx/Wanted/login', 'POST', {
    code: code,
    jsonData: JSON.stringify(userRes)
  })
}
// 获取全局配置
const globalData = obj => Request('Xcx/Wanted/globalData', 'GET', obj)
// 发送fromid
const saveFormId = obj => Request('Xcx/Wanted/saveFormId', 'POST', obj)
// 小程序登录
const wxLogin = (user) => {
  user.iv = encodeURIComponent(user.iv)
  return new Promise((res, rej) => {
    Promise.all([wxPromisify(wx.login)])
      .then(data => {
        return Login(data[0].code, user)
      })
      .then(data => {
        res(data)
      })
  })
}

export default {
  wxLogin,
  saveFormId,
  globalData
}
